const api = require('../api/api');
const constants = require('../constants/constants');

/**
 * 调用普通接口
 * @param {*} url 
 * @param {*} method 
 * @param {*} data 
 * @param {*} header 
 */
function fun(url, method, data, header) {
  data = data || {};
  header = header || {
    'content-type': 'application/json'
  };
  let promise = new Promise(function (resolve, reject) {
    // 正常调用接口
    wx.request({
      url: url,
      header: header,
      data: data,
      method: method,
      success: function (res) {
        // 如果未经授权或token过期，需要重新授权，跳转回/pages/index/index页面
        if (res.data.success == false || res.data.code == constants.httpStatus.unauthorized) {
          console.warn('未经授权或token过期，需要重新授权');
          wx.reLaunch({
            url: "/pages/index/index?authViewShow=true"
          });
          reject(res);
        }

        // 如果已授权并且token没有过期，则正常执行
        resolve(res);
      }
    });
  });

  promise.action = async function(func){
    // 接收action的返回值，如果没有返回值则为undefined
    let actionValue = await promise.then(func);
    if (api.log.enable) {
      if (url.includes(api.data.url.login.wechatJscode2session.substring(0, 29))) {
        // 如果是调用登录接口，则添加用户登录日志和接口调用日志
        let userInfo = wx.getStorageSync('userInfo');
        saveWeChatJscode2SessionLog(userInfo);
        saveInterfaceCallLog({
          openid: userInfo.openid, 
          url: api.data.prefix + api.data.url.login.wechatJscode2session,
          param: userInfo.jsCode,
          method: 'POST'
        });
      } else {
        // 如果是其他返回数据的接口，则添加接口调用日志
        let user = wx.getStorageSync('userInfo');
        let param = {
          userId: user.userId,
          // 用于解决接口格式为/api/diagnose/{codeOrName}的情况
          url: (actionValue && actionValue.url) ? actionValue.url : url,
          header: header,
          data: data,
          method: method,
        };
        saveInterfaceCallLog(param);
      }
      return promise;
    }
  };

  return promise;
}

/**
 * 调用上传文件的接口
 * @param {*} url 
 * @param {*} name 
 * @param {*} filePath 
 */
function upload(url, name, filePath) {
  let header = {};
  // wx.showNavigationBarLoading();
  let promise = new Promise(function (resolve, reject) {
    // 正常调用接口
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: name,
      header: header,
      success: function (res) {
        resolve(res);
      }
    });
  });

  promise.then((result) => {
    // 添加接口调用日志
    // saveInterfaceCallLog(data);
  });

  return promise;
}

/**
 * 微信登录日志
 */
function saveWeChatJscode2SessionLog(data) {
  wx.request({
    url: api.log.prefix + api.log.url.saveWeChatJscode2SessionLog,
    header: {
      'content-type': 'application/json'
    }, // 还没有决定header里要不要加user
    data: data,
    method: 'post',
    success: function (res) {}
  });
}

/**
 * 添加登录日志
 */
function saveUserLoginLog(data) {
  wx.request({
    url: api.log.prefix + api.log.url.saveUserLoginLog,
    header: {
      'content-type': 'application/json'
    }, // 还没有决定header里要不要加user
    data: data,
    method: 'post',
    success: function (res) {}
  });
}

/**
 * 添加接口调用日志
 */
function saveInterfaceCallLog(data) {
  wx.request({
    url: api.log.prefix + api.log.url.saveInterfaceCallLog,
    header: {
      'content-type': 'application/json'
    }, // 还没有决定header里要不要加user
    data: data,
    method: 'post',
    success: function (res) {}
  });
}

module.exports = {
  get: function (url, data, header) {
    return fun(url, "GET", data, header);
  },
  post: function (url, data, header) {
    return fun(url, "POST", data, header);
  },
  upload: function (url, name, filePath) {
    return upload(url, name, filePath);
  }
};